//
//  ZqlWBRefreshControl.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/26.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit
import SnapKit


enum wbRefreshStatue:Int{
    case Normal = 1   //正常的初始状态
    
    case Pulling = 2  //准备刷新的状态
    
    case Refreshing = 3 //正在刷新的状态
    
}

class ZqlWBRefreshControl: UIControl {
    
    
    //状态属性
    var statue: wbRefreshStatue = .Normal{
        didSet{
            switch statue{
            case .Normal:tipLable.text = "下拉刷新"
            //显示箭头
            arrowIcon.hidden = false
            //停止菊花转动
            indicationView.stopAnimating()
            //让箭头回到原来的方向
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrowIcon.transform = CGAffineTransformIdentity
                
            })
            //回复父视图的inset
            if oldValue == .Refreshing{
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top -= self.refreshHeight
                    self.scrollView?.contentInset = inset
                    
                })
                }
            case .Pulling:tipLable.text = "松开刷新"
            //旋转箭头方向  系统默认的动画时间  0.25
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
            })
                
            case .Refreshing:tipLable.text = "正在刷新"
            
            self.sendActionsForControlEvents(.ValueChanged)
            //隐藏箭头
            self.arrowIcon.hidden = true
            //转动菊花
            indicationView.startAnimating()
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                var inset = self.scrollView!.contentInset
                inset.top += self.refreshHeight
                self.scrollView?.contentInset = inset
            })
            }
        }
    }
    
    private let refreshHeight:CGFloat = 60
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y:-refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var scrollView:UIScrollView?
    
    //结束转动
    func endRefresh(){
        //延时执行
        let time_t = dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC)*0.3))
        dispatch_after(time_t, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
            
            scrollView = myFather
            //添加观察者  观察srollView的contentOffset属性
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    //观察者响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //获取tableView垂直方向的位移
        let offsetY = scrollView?.contentOffset.y ?? 0
        //临界值是124
        let conaditionValue = -((scrollView?.contentInset.top ?? 0) + refreshHeight)
        //判断是否在拽动
        if scrollView!.dragging {
            if statue == .Normal && conaditionValue > offsetY{
                
                statue = .Pulling
            }else if statue == .Pulling && conaditionValue < offsetY {
                statue = .Normal
            }
        }else{
            if statue == .Pulling{
                statue = .Refreshing
            }
        }
    }
    
    //移除观察者
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //加载界面
    private func setUpUI(){
        addSubview(tipLable)
        addSubview(arrowIcon)
        addSubview(indicationView)
        addSubview(backImageView)
        
        //添加约束
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
        }
        
        tipLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLable.snp_left).offset(5)
            make.centerY.equalTo(tipLable.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
        
    }
    //懒加载子视图
    private lazy var tipLable:UILabel = UILabel(text: "下拉刷新", fontSize: 14, textColor: UIColor.darkGrayColor())
    
    private lazy var arrowIcon:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var backImageView:UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
    private lazy var indicationView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
}

